#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import subprocess
import os
import sys


#### handle parameters and standard values ####
## ARGS
parser = argparse.ArgumentParser(description='Omnibus Garage', add_help=True)
parser.add_argument('--backend', '-b', action="store", dest="backend")
parser.add_argument('--config', '-c', action="store", dest="config_dir")
parser.add_argument('--ui', '-x', action="store", dest="ui", default=False)
parser.add_argument('--hello', action="store", dest="hello", default=False)
parser.add_argument('--svn', action="store_true", default=False)
parser.add_argument('--cli', action="store_true", default=False)

# parse
ARGS = parser.parse_args()

### variables & std values
## init
ui_paths = False
hello_path = False

## svn mode
if ( ARGS.svn ):
    err = False
    print "Running Omnibus-Frontends from SVN-directory."
    
    # find svn frontend dir
    arg_0_path = os.path.dirname(sys.argv[0])
    if ( arg_0_path ):
        arg_0_path += "/"
    svn_frontend_dir = os.path.realpath( arg_0_path + "../.." )  ## oder os.path.abspath, je nachdem..

    # check for: hello
    svn_hello_path = svn_frontend_dir + "/garage/omnibus_hello/hello.py"
    if ( os.path.isfile(svn_hello_path) ):
        print "Found »hello.py« at '" + svn_hello_path + "'"
        hello_path = svn_hello_path
    else:
        print "ERROR: Couldn't find »hello.py« at '" + hello_path + "'"
        err = True
    
    # BRANCH: UI -> cli
    if ( ARGS.cli ):
        svn_cli_path = svn_frontend_dir + "/cli/cli.py"
        if ( os.path.isfile(svn_cli_path) ):
            print "Found »cli.py« at '" + svn_cli_path + "'"
            ui_paths = svn_cli_path
        else:
            print "ERROR: Couldn't find »cli.py« at '" + svn_cli_path + "'"
            err = True
    # BRANCH: UI -> gui
    else:
        svn_gui_path = svn_frontend_dir + "/omnibus-driver/omnibus_driver_main.py"
        if ( os.path.isfile(svn_gui_path) ):
            print "Found »omnibus_driver_main.py« at '" + svn_gui_path + "'"
            ui_paths = svn_gui_path
        else:
            print "ERROR: Couldn't find »omnibus_driver_main.py« at '" + svn_gui_path + "'"
            err = True
        
    
    ## cancel on errors
    if ( err ):
        print "quit."
        exit(1)


## backend
if ( ARGS.backend ):
    backend_path = os.path.realpath(ARGS.backend)
elif ( os.path.isfile("/usr/bin/omnibus-bin") ):
    backend_path = "/usr/bin/omnibus-bin"
else:
    print "ERROR: Can't find Omnibus-Backend."
    print "quit."
    exit(1)
    
## config-dir
if ( ARGS.config_dir ):
    config_dir = ARGS.config_dir
else:
    config_dir = os.path.expanduser("~/.omnibus")

## UIs         ## TODO werden später ggf mehrere UIs
if ( not ui_paths ):
    if ( ARGS.ui ):
        ui_paths = ARGS.ui
    elif os.path.isfile("/usr/bin/omnibus_driver_main.py"):
        ui_paths = "/usr/bin/omnibus_driver_main.py"
    else:
        print "ERROR: Can't find any Omnibus-UI."
        print "quit."
        exit(1)

## hello
if ( not hello_path ):
    if ( ARGS.hello ):
        hello_path = ARGS.hello
    elif os.path.isfile("/usr/share/pyshared/omnibus_hello/hello.py"):
        hello_path = "/usr/share/pyshared/omnibus_hello/hello.py"
    else:
        hello_path = ""
### [variables & std values]


#### on first start-up: create config-dir and configurations ####
## check config_dir, create one if necessary
try:
    if ( not os.path.isdir(config_dir) ):
        print "'" + config_dir + "' does not exist, trying to create..."
        os.mkdir(config_dir)
        print "done."
except ( OSError ):
    print "ERROR: Can't create config-dir."
    print "quit."
    exit(1)

## check for config.xml, run hello if necessary
if ( not os.path.isfile(config_dir + "/config.xml") ):
    print "Initial run.. calling the hello-program to create new settings..."
    if ( hello_path ):
        if ( ARGS.cli ):
            hello_cli = "--cli"
        else:
            hello_cli = "--gui"
            
        # * call hello *
        subprocess.call(("/usr/bin/python", hello_path, "--config", config_dir, hello_cli))
    else:
        print "ERROR: Can't find »omnibus-hello«, the settings creator."
        print "quit."
        exit(1)
        
    # quit, if hello didn't produce a »config.xml«-file
    if ( not os.path.isfile(config_dir + "/config.xml") ):
        print "ERROR: »omnibus-hello« didn't create an »config.xml«-file."
        print "quit."
        exit(1)
#### [on first start-up]



#### start applications (if necessary) ####
## TODO schauen ob backend schon läuft..

## "incoming/" should be always there
if ( not os.path.isdir(config_dir+"/incoming") ):
    print "create 'incoming/'..."
    os.mkdir(config_dir+"/incoming")
    print "done."

## start backend
print "> starting omnibus-backend (" + backend_path + ")"
logfile = open(config_dir+"/omnibus.log", "w")
subprocess.Popen((backend_path,), executable=backend_path, stdout=logfile, cwd=config_dir)


## start frontend
print "> starting UI"
#subprocess.Popen(("/home/mario/Computer/Programme/omnibus/start.sh", ui_paths, config_dir+"/unix.sock"), executable="python")
#ui_proc = subprocess.Popen(("firefox", ui_paths, config_dir+"/unix.sock"), executable="/usr/bin/python")
os.execv("/usr/bin/python", ["/usr/bin/python", ui_paths, config_dir+"/unix.sock"])      ## XXX für gnome3

## TODO wenn bei exec was schief läuft, omnibus-bin killen.

#ui_proc.wait() ## XXX soll das hier bleiben?
#print "bye."

